package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.utils.CodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author laoYe
 * @date 2025-10-21
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
       log.info("办理入住详情{}：",dto);
       CheckInElderDto checkInApplyDto=dto.getCheckInElderDto();
       //先判断老人是否存在老人表
        Elder elder=elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo,checkInApplyDto .getIdCardNo()));
        if (elder != null){
            if (elder.getStatus()>=2 && elder.getStatus()<=4){
                throw new RuntimeException("老人已入住");
            }
        }//老人不在表格里，添加老人
        //还要判断床位是否被占用
        Long bedid=dto.getCheckInConfigDto().getBedId();
        int cont=bedMapper.updateBedStatus(bedid);
        if (cont==0){
            throw new RuntimeException("床位已占用");
        }
        //判断结束后，可以开始添加信息
        Elder elder1=addOrupdateElder(checkInApplyDto,bedid,elder);
        //添加入住信息
        CheckIn checkIn=addCheckIn(dto,elder1);
        //添加签约办理
        addContract(dto,elder1,checkIn);
        //添加入住配置
        addCheckInConfig(dto,checkIn);



    }


    // 查询用户入住详情
    @Override
    public CheckInDetailVo getChckInDetail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        // 查询老人信息
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getId, checkIn.getElderId()));
        Date birthday = DateUtils.getBirthdayFromIdCard(elder.getIdCardNo());
        if (birthday != null) {
            elder.setAge(DateUtils.getAge(birthday));
        }
        // 查询入住配置信息
        CheckInConfig config = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>()
                .eq(CheckInConfig::getCheckInId, id));
        //  查询签约办理信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getCheckInId, id));

        // 5. 解析紧急联系人（remark 字段为 JSON）
        List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);


        // 组装返回数据
        CheckInDetailVo vo=new CheckInDetailVo();
        vo.setCheckInElderVo(BeanUtil.toBean(elder, CheckInElderVo.class));
        vo.setCheckInConfigVo(BeanUtil.toBean(config, CheckInConfigVo.class));
        vo.setContract(BeanUtil.toBean(contract, Contract.class));
        vo.setElderFamilyVoList(familyList);

        return vo;
    }



    private void addCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        log.info("添加入住配置：{}", JSON.toJSONString(checkInConfig));
    }

    private void addContract(CheckInApplyDto dto, Elder elder1, CheckIn checkIn) {
      Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
      contract.setCheckInId(checkIn.getId());
      contract.setElderId(elder1.getId());
      String contractNumber = CodeGenerator.generateContractNumber();
      contract.setContractNumber(contractNumber);

      contract.setElderName(checkIn.getElderName());
      contract.setStartDate(checkIn.getStartDate() );
      contract.setEndDate(checkIn.getEndDate());

      contract.setStatus(0);

      contract.setCreateTime(new Date());
      contract.setUpdateTime(contract.getCreateTime());
      contractMapper.insert(contract);


    }

    // 添加入住信息
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elder1) {

        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);//
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());

        checkIn.setIdCardNo(dto.getCheckInElderDto().getIdCardNo());//这里为什么不直接用 elder.getIdCardNo()

        checkIn.setBedNumber(elder1.getBedNumber());
        checkIn.setStatus(0);
        //紧急联系人
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        save(checkIn);

        return checkIn;
    }

    private Elder addOrupdateElder(CheckInElderDto checkInElderDto, Long bedid, Elder elder) {
        Elder elder1 = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder1.setStatus(1);
        // 设置 床位id
        elder1.setBedId(bedid);
        // 设置床位编号
        elder1.setBedNumber(bedMapper.selectBedById(bedid).getBedNumber());
        if (null == elder) {
            elder1.setCreateTime(new Date());
            elderMapper.insertElder(elder1);
        } else {
            elder1.setUpdateTime(new Date());
            elder1.setId(elder.getId());
            elderMapper.updateById(elder1);
            log.info("更新老人信息成功,id={}", elder1.getId());
        }
        return elder1;

    }
}
